package com.cykj.service;

import jakarta.annotation.PreDestroy;
import lombok.Data;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Service
public class InterviewSessionService {
    private final Map<String, InterviewSession> sessions = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private static final long SESSION_TIMEOUT = 15 * 60 * 1000; // 15分钟无活动超时

    @Data
    public static class InterviewSession {
        private String sessionId;
        private String job;
        private List<String> questions = new CopyOnWriteArrayList<>();
        private List<String> askedQuestions = new CopyOnWriteArrayList<>();
        private List<String> userAnswers = new CopyOnWriteArrayList<>();
        private int currentQuestionIndex = 0;
        private boolean isCompleted = false;
        private long lastActiveTime = System.currentTimeMillis();
        private ScheduledFuture<?> timeoutTask;

        public void updateActiveTime() {
            this.lastActiveTime = System.currentTimeMillis();
        }
    }

    /**
     * 创建或获取会话（自动启动超时检测）
     */
    public InterviewSession createOrGetSession(String sessionId, String job, List<String> questions) {
        return sessions.computeIfAbsent(sessionId, id -> {
            InterviewSession session = new InterviewSession();
            session.setSessionId(sessionId);
            session.setJob(job);
            session.setQuestions(new CopyOnWriteArrayList<>(questions));
            scheduleSessionTimeout(session);
            return session;
        });
    }

    /**
     * 获取并更新会话活跃时间（用于心跳检测）
     */
    public InterviewSession getAndUpdateSession(String sessionId) {
        InterviewSession session = sessions.get(sessionId);
        if (session != null && !session.isCompleted()) {
            session.updateActiveTime();
            rescheduleSessionTimeout(session);
        }
        return session;
    }

    /**
     * 获取会话（不更新活跃时间）
     */
    public InterviewSession getSession(String sessionId) {
        return sessions.get(sessionId);
    }

    /**
     * 清理会话
     */
    public void clearSession(String sessionId) {
        InterviewSession session = sessions.remove(sessionId);
        if (session != null && session.getTimeoutTask() != null) {
            session.getTimeoutTask().cancel(false);
        }
    }

    /**
     * 获取会话统计信息
     */
    public Map<String, Object> getSessionStats() {
        long now = System.currentTimeMillis();
        return Map.of(
                "totalSessions", sessions.size(),
                "activeSessions", sessions.values().stream()
                        .filter(s -> !s.isCompleted()).count(),
                "expiredSessions", sessions.values().stream()
                        .filter(s -> now - s.getLastActiveTime() > SESSION_TIMEOUT)
                        .count()
        );
    }

    // ============ 私有方法 ============

    private void scheduleSessionTimeout(InterviewSession session) {
        session.setTimeoutTask(scheduler.schedule(() -> {
            if (shouldExpire(session)) {
                sessions.remove(session.getSessionId());
                System.out.println("会话超时已清理: " + session.getSessionId());
            }
        }, SESSION_TIMEOUT, TimeUnit.MILLISECONDS));
    }

    private void rescheduleSessionTimeout(InterviewSession session) {
        if (session.getTimeoutTask() != null) {
            session.getTimeoutTask().cancel(false);
        }
        scheduleSessionTimeout(session);
    }

    private boolean shouldExpire(InterviewSession session) {
        return System.currentTimeMillis() - session.getLastActiveTime() >= SESSION_TIMEOUT;
    }

    @PreDestroy
    public void destroy() {
        scheduler.shutdownNow();
        sessions.clear();
    }
}